package com.redlight.base;

import com.alibaba.fastjson.annotation.JSONField;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chao on 2019/1/9.
 */
public abstract class TreeEntity<T> extends BaseEntity  {
    private static final long serialVersionUID = 1L;
    public static final String rootId = "0";
    protected T parent;
    protected String parentIds;
    protected String name;
    protected Integer sort;
    protected Integer level;
    protected List children = new ArrayList();

    public TreeEntity() {
        this.sort = Integer.valueOf(30);
    }

    public TreeEntity(String id) {
        super(id);
    }

    public abstract T getParent();

    public abstract void setParent(T var1);

    public String getParentIds() {
        return this.parentIds != null?this.parentIds:"";
    }

    public void setParentIds(String parentIds) {
        this.parentIds = parentIds;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getSort() {
        return this.sort;
    }

    public void setSort(Integer sort) {
        this.sort = sort;
    }

    public Integer getLevel() {
        return this.level;
    }

    public void setLevel(Integer level) {
        this.level = level;
    }

    public String getParentId() {
        String id = null;
        if(this.getParent() != null) {
            id = (String)Reflections.getFieldValue(this.getParent(), "id");
        }

        return StringUtils.isNotBlank(id)?id:"0";
    }

    public List getChildren() {
        return this.children;
    }

    public void setChildren(List children) {
        this.children = children;
    }

    @JSONField(
            serialize = false
    )
    public static void sortList(List list, List<? extends TreeEntity> sourcelist, String parentId, boolean cascade) {
        for(int i = 0; i < sourcelist.size(); ++i) {
            TreeEntity e = (TreeEntity)sourcelist.get(i);
            if(e.getParentId() != null && e.getParentId().equals(parentId)) {
                list.add(e);
                if(cascade) {
                    for(int j = 0; j < sourcelist.size(); ++j) {
                        TreeEntity child = (TreeEntity)sourcelist.get(j);
                        if(child.getParentId() != null && child.getParentId().equals(e.getId())) {
                            sortList(list, sourcelist, e.getId(), true);
                            break;
                        }
                    }
                }
            }
        }

    }
}
